<!DOCTYPE html>
<html lang="en">
<head>
    <title>Search an airport</title>
    <style>
        * {
            box-sizing: border-box;
        }

        .container {
            width: 300px;
        }

        body {
            font-family: Arial, sans-serif;
        }

        .search-input {
            display: block;
            width: 100%;
            height: 50px;
            padding: 5px;
            font-size: 16px;
        }

        .select {
            display: block;
            width: 100%;
            margin-top: 10px;
            padding: 0;
            border: none;
        }

        .error {
            margin-top: 10px;
            color: red;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>Search an airport</h1>

    <input type="text" class="search-input" id="searchQuery" placeholder="Type a query" autocomplete="off">
    <select class="select" id="airportList" size="5">
    </select>
    <div class="error" id="error"></div>
</div>
<script>
    const searchInput = document.getElementById('searchQuery');
    const airportList = document.getElementById('airportList');
    const errorElement = document.getElementById('error');

    const debounce = (func, delay) => {
        let debounceTimer;

        return function () {
            const context = this;
            const args = arguments;
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => func.apply(context, args), delay);
        }
    }

    searchInput.addEventListener('input', debounce(function () {
        if (this.value.length < 2) {
            airportList.innerHTML = '';
            errorElement.textContent = '';
            return;
        }

        fetch(`/api/search/?query=${this.value}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error, status = ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                airportList.innerHTML = '';
                errorElement.textContent = '';
                data.data.forEach(airport => {
                    const option = document.createElement('option');
                    option.text = `${airport.cityName.en} (${airport.code}), ${airport.country}`;
                    option.value = airport.code;
                    airportList.add(option);
                });
            })
            .catch(error => {
                console.error(error);
                errorElement.textContent = 'Error while searching. Please try again later.';
            });
    }, 300));
</script>
</body>
</html>
